package com.idea.relax.tool.core;

import org.springframework.lang.Nullable;

import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * @className: Try
 * @description:
 * @author: salad
 * @date: 2022/2/19
 **/
public class Try {

    public static <T, R> Function<T, R> it(UncheckedFunction<T, R> mapper) {
        Objects.requireNonNull(mapper);
        return (t) -> {
            try {
                return mapper.apply(t);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        };
    }

    public static <T> Consumer<T> it(UncheckedConsumer<T> mapper) {
        Objects.requireNonNull(mapper);
        return (t) -> {
            try {
                mapper.accept(t);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        };
    }

    public static <T> Supplier<T> it(UncheckedSupplier<T> mapper) {
        Objects.requireNonNull(mapper);
        return () -> {
            try {
                return mapper.get();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        };
    }


    @FunctionalInterface
    public interface UncheckedSupplier<T> {
        @Nullable
        T get() throws Exception;
    }

    @FunctionalInterface
    public interface UncheckedConsumer<T> {
        @Nullable
        void accept(@Nullable T t) throws Exception;
    }

    @FunctionalInterface
    public interface UncheckedFunction<T, R> {
        @Nullable
        R apply(@Nullable T t) throws Exception;
    }

}
